package svc

import (
	"community-service/cmd/api/internal/config"
	auth "gitee.com/vzerx/proto-contracts/auth"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/zrpc"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

type ServiceContext struct {
	Config config.Config
	User   auth.UserManagerClient

	DB *gorm.DB
}

func NewServiceContext(c config.Config) *ServiceContext {
	db := NewDB(c)

	authConn := zrpc.MustNewClient(c.AuthRpcConf)

	return &ServiceContext{
		Config: c,
		User:   auth.NewUserManagerClient(authConn.Conn()),

		DB: db,
	}
}

func NewDB(c config.Config) *gorm.DB {
	db, _ := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{
		SkipDefaultTransaction: true,
		PrepareStmt:            true,
		Logger:                 logger.Default.LogMode(logger.Info),
	})
	sqlDB, err := db.DB()
	if err != nil {
		logx.Must(err)
	}
	sqlDB.SetMaxIdleConns(100)   // 设置打开数据库连接的最大数量
	sqlDB.SetMaxOpenConns(10000) //  设置了连接可复用的最大时间
	sqlDB.SetConnMaxLifetime(time.Hour)
	return db
}
